package org.hismig.view;

import java.util.List;

import javax.swing.table.AbstractTableModel;

import org.hismig.migration.Context;
import org.hismig.migration.executor.DBExecutor;
import org.hismig.migration.result.JobResultInfo;
import org.hismig.scheduler.ITrigger;
import org.hismig.scheduler.ITriggerListener;
import org.hismig.utils.DateTool;

/**
 * @declare: //TODO <br />
 *           This class created by Vansion.Hopihit on 2012-8-10 <br />
 *           <a href="mailto:vansionhopihit@gmail.com">Contact Me</a>
 * @version 1.0
 * @author Vansion.Hopihit
 * 
 */
public class JobTableModel extends AbstractTableModel
		implements
			ITriggerListener {

	private static final long serialVersionUID = -2379313394986141292L;
	private final String[] columnNames;
	private final ITrigger[] triggers;

	public JobTableModel(ITrigger trigger) {
		this(new ITrigger[]{trigger});
	}

	@Override
	public void beforeTriggerStart(Context context, List<DBExecutor> dbExecutors) {
	}

	@Override
	public void afterTriggerEnd(JobResultInfo jobResultInfo) {
		for (int i = 0; i < triggers.length; i++) {
			fireTableCellUpdated(i, 1);
			fireTableCellUpdated(i, 2);
		}
	}

	public JobTableModel(ITrigger[] triggers) {
		this.triggers = triggers;

		for (ITrigger trigger : triggers) {
			if (null != trigger) {
				trigger.addListener(this);
			}
		}

		columnNames = new String[]{"定时器", "下次运行时间", "上次运行时间"};
	}

	@Override
	public String getColumnName(int column) {
		if (column < columnNames.length) {
			return columnNames[column];
		}

		return String.valueOf(column);
	}

	public int getColumnCount() {
		return columnNames.length;
	}

	public int getRowCount() {
		if (null != triggers) {
			return triggers.length;
		}

		return 1;
	}

	public Object getValueAt(int rowIndex, int columnIndex) {
		if (null != triggers && triggers.length > rowIndex) {

			ITrigger trigger = triggers[rowIndex];

			if (null != trigger) {

				switch (columnIndex) {
					case 0 :
						return trigger.getName();

					case 1 :
						return DateTool.getNormalDateTime(trigger
								.getNextFireTime());

					case 2 :
						return DateTool.getNormalDateTime(trigger
								.getPreviousFireTime());
				}
			} else {

				switch (columnIndex) {
					case 0 :
						return "TriggerClass";

					case 1 :
						return "2001-01-01 00:00:00";

					case 2 :
						return "2001-01-01 00:00:00";
				}

			}
		}

		return null;
	}

}
